package com.ds.esd.admin.plugins.service;

import com.ds.common.JDSException;
import com.ds.common.database.ProfiledConnectionEntry;
import com.ds.common.database.metadata.*;
import com.ds.common.util.StringUtility;
import com.ds.config.ErrorListResultModel;
import com.ds.config.ErrorResultModel;
import com.ds.config.ListResultModel;
import com.ds.config.ResultModel;
import com.ds.enums.db.MethodChinaName;
import com.ds.esd.admin.plugins.fdt.node.UIColNode;
import com.ds.esd.admin.plugins.fdt.node.UITableNode;
import com.ds.esd.admin.plugins.fdt.node.UITopNode;
import com.ds.esd.client.ESDClient;
import com.ds.esd.client.ESDFacrory;
import com.ds.esd.client.ProjectVersion;
import com.ds.esd.project.config.DataBaseConfig;
import com.ds.web.util.PageUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping(value = {"/admin/fdt/magager/"})
@MethodChinaName(cname = "数据库表操作")
public class DBManagerService implements TableService {


    @MethodChinaName(cname = "删除数据库表")
    @RequestMapping(method = RequestMethod.POST, value = "DropTable")
    public @ResponseBody
    ResultModel<Boolean> dropTable(String name, String configKey) {
        ResultModel<Boolean> result = new ResultModel<Boolean>();
        try {

            String[] tableNameArr = StringUtility.split(name, ";");
            MetadataFactory factory = getClient().getDbFactory(configKey);
            factory.dropTable(Arrays.asList(tableNameArr));
        } catch (Exception e) {
            e.printStackTrace();
            ErrorResultModel<Boolean> errorResult = new ErrorResultModel<Boolean>();
            errorResult.setErrdes(e.getMessage());
            result = errorResult;
        }
        return result;
    }


    @Override
    @MethodChinaName(cname = "编辑库表信息")
    @RequestMapping(method = RequestMethod.POST, value = "EditTable")
    public @ResponseBody
    ResultModel<Boolean> editTable(@RequestBody TableInfo tableInfo) {
        ResultModel<Boolean> result = new ResultModel<Boolean>();
        try {

            List<TableInfo> tableList = new ArrayList<TableInfo>();
            tableList.add(tableInfo);
            String configKey = tableInfo.getConfigKey();
            if (configKey == null || configKey.equals("")) {
                configKey = tableInfo.getUrl();
            }
            MetadataFactory factory = getClient().getDbFactory(tableInfo.getConfigKey());
            factory.modifyTableCnname(tableList);
        } catch (Exception e) {
            e.printStackTrace();
            ErrorResultModel<Boolean> errorResult = new ErrorResultModel<Boolean>();
            errorResult.setErrdes(e.getMessage());
            result = errorResult;
        }
        return result;
    }


    @Override
    @MethodChinaName(cname = "添加数据库表")
    @RequestMapping(method = RequestMethod.POST, value = "AddTable")
    public @ResponseBody
    ResultModel<Boolean> addTable(@RequestBody TableInfo tableInfo) {
        ResultModel<Boolean> result = new ResultModel<Boolean>();
        try {
            String configKey = tableInfo.getConfigKey();
            if (configKey == null || configKey.equals("")) {
                configKey = tableInfo.getUrl();
            }
            MetadataFactory factory = getClient().getDbFactory(configKey);
            factory.createTableByInfo(tableInfo);
        } catch (Exception e) {
            ErrorResultModel<Boolean> errorResult = new ErrorResultModel<Boolean>();
            errorResult.setErrdes(e.getMessage());
            result = errorResult;
        }


        return result;
    }

    @Override
    @MethodChinaName(cname = "添加列")
    @RequestMapping(method = RequestMethod.POST, value = "AddCol")
    public @ResponseBody
    ResultModel<Boolean> addCol(@RequestBody ColInfo col) {
        ResultModel<Boolean> result = new ResultModel<Boolean>();
        try {

            List<ColInfo> cols = new ArrayList<ColInfo>();
            cols.add(col);
            String configKey = col.getConfigKey();
            if (configKey == null || configKey.equals("")) {
                configKey = col.getUrl();
            }

            MetadataFactory factory = getClient().getDbFactory(configKey);
            factory.modifyTableCols(col.getTablename(), cols);
        } catch (Exception e) {
            ErrorResultModel<Boolean> errorResult = new ErrorResultModel<Boolean>();
            errorResult.setErrdes(e.getMessage());
            result = errorResult;
        }

        return result;
    }

    @Override
    @MethodChinaName(cname = "获取所有列")
    @RequestMapping(method = RequestMethod.POST, value = "GetAllCollByTableName")
    public @ResponseBody
    ListResultModel<List<ColInfo>> getAllCollByTableName(String tablename, String configKey) {
        ListResultModel<List<ColInfo>> result = new ListResultModel<List<ColInfo>>();
        try {
            MetadataFactory factory = getClient().getDbFactory(configKey);
            List<ColInfo> cols = factory.getTableInfo(tablename).getColList();
            result = PageUtil.getDefaultPageList(cols);
        } catch (Exception e) {
            ErrorListResultModel<List<ColInfo>> errorResult = new ErrorListResultModel<List<ColInfo>>();
            errorResult.setErrdes(e.getMessage());
            result = errorResult;
        }


        return result;
    }

    @Override
    @MethodChinaName(cname = "获取所有数据库表")
    @RequestMapping(method = RequestMethod.POST, value = "GetAllTableByName")
    @ResponseBody
    public ListResultModel<List<TableInfo>> getAllTableByName(String simpleName, String configKey) {
        ListResultModel<List<TableInfo>> result = new ListResultModel<List<TableInfo>>();
        List<TableInfo> tables = null;
        try {

            MetadataFactory factory = getClient().getDbFactory(configKey);
            tables = factory.getTableInfos(simpleName);
            result = PageUtil.getDefaultPageList(tables);
        } catch (Exception e) {
            ErrorListResultModel<List<TableInfo>> errorResult = new ErrorListResultModel<List<TableInfo>>();
            errorResult.setErrdes(e.getMessage());
            result = errorResult;
        }

        return result;
    }

    @Override
    @MethodChinaName(cname = "获取所有数据库表")
    @RequestMapping(method = RequestMethod.POST, value = "getProjectTables")
    public @ResponseBody
    ListResultModel<List<TableInfo>> getProjectTables(String configName, @PathVariable String projectName) {
        ListResultModel<List<TableInfo>> result = new ListResultModel<List<TableInfo>>();
        try {
            ProjectVersion version = getClient().getProjectVersionByName(projectName);
            DataBaseConfig dataBaseConfig = version.getProject().getConfig().getDataBaseConfigBykey(configName);
            if (dataBaseConfig == null) {
                throw new JDSException(" 数据库配置错误");
            }

            List<String> tableNames = dataBaseConfig.getTableName();
            MetadataFactory factory = getClient().getDbFactory(configName);
            List<TableInfo> projecttables = new ArrayList<TableInfo>();

            List<TableInfo> tables = factory.getTableInfos(null);
            for (TableInfo table : tables) {
                if (tableNames == null || tableNames.contains(table.getName())) {
                    projecttables.add(table);
                }

            }

            result = PageUtil.getDefaultPageList(projecttables);
        } catch (Exception e) {
            ErrorListResultModel<List<TableInfo>> errorResult = new ErrorListResultModel<List<TableInfo>>();
            errorResult.setErrdes(e.getMessage());
            result = errorResult;
        }

        return result;
    }

//    @Override
//    @MethodChinaName(cname = "创建JAVA映射对象")
//    @RequestMapping(method = {RequestMethod.POST, RequestMethod.GET},value = "CreateModule")
//    public @ResponseBody
//    ResultModel<Boolean> createModule(@RequestBody TempBean tempBean, String dbConfigName, String projectName) {
//        ResultModel<Boolean> result = new ResultModel<Boolean>();
//
//        try {
//            ProjectVersion version = getClient().getProjectVersionByName(projectName);
//            String tableNameStr = tempBean.getTableName();
//            GenJava tableAndJava = new GenJava(tempBean.getSchema());
//            if (tableNameStr.indexOf(";") > -1) {
//                String[] tableNames = StringUtility.split(tableNameStr, ";");
//
//                for (String tableName : tableNames) {
//                    tempBean.setTableName(tableName);
//                    TempRoot root = new TempRoot(tempBean);
//                    tableAndJava.createJavaByInfo(root,"java");
//                }
//            }
//
//
//        } catch (Exception e) {
//            ErrorResultModel<Boolean> errorResult = new ErrorResultModel<Boolean>();
//            errorResult.setErrdes(e.getMessage());
//            result = errorResult;
//        }
//        return result;
//    }
//

    @Override
    @MethodChinaName(cname = "获取数据库分类节点")
    @RequestMapping(value = "GetDbTrees", method = {RequestMethod.POST, RequestMethod.GET})
    public @ResponseBody
    ListResultModel<List<UITopNode>> GetDbTrees(String projectName) {
        ListResultModel<List<UITopNode>> result = new ListResultModel<List<UITopNode>>();

        List<UITopNode> tableNodes = new ArrayList<UITopNode>();
        try {
            String[] nameStrs = new String[]{"BPM", "FDT", "RO", "VFS", "HA", "ADMIN", "RT", "TDA"};
            for (String text : nameStrs) {
                UITopNode simpNode = new UITopNode(text + "_", text, projectName, "console");
                tableNodes.add(simpNode);
            }
            result.setData(tableNodes);
        } catch (Exception e) {
            ErrorListResultModel<List<UITopNode>> errorResult = new ErrorListResultModel<List<UITopNode>>();
            errorResult.setErrdes(e.getMessage());
            result = errorResult;
        }
        return result;
    }

    @Override
    @MethodChinaName(cname = "获取数据库树形实例数据")
    @RequestMapping(value = "GetTableTrees", method = {RequestMethod.POST, RequestMethod.GET})
    public @ResponseBody
    ListResultModel<List<UITableNode>> getTableTrees(String text, String configKey, @PathVariable String projectName) {

        ListResultModel<List<UITableNode>> result = new ListResultModel<List<UITableNode>>();
        List<UITableNode> tableNodes = new ArrayList<UITableNode>();

        try {
            ProjectVersion version = getClient().getProjectVersionByName(projectName);

            DataBaseConfig dataBaseConfig = version.getProject().getConfig().getDataBaseConfigBykey(configKey);
            if (dataBaseConfig == null) {
                throw new JDSException(" 数据库配置错误");
            }

            if (text == null) {
                text = dataBaseConfig.getSimpleName();
            }
            List<String> tableNames = dataBaseConfig.getTableName();
            MetadataFactory factory = getClient().getDbFactory(configKey);

            List<TableInfo> tables = factory.getTableInfos(text);
            for (TableInfo table : tables) {
                if (tableNames == null || tableNames.contains(table.getName())) {
                    UITableNode tabelui = new UITableNode(table);
                    tableNodes.add(tabelui);
                }

            }


            result.setData(tableNodes);
        } catch (Exception e) {
            ErrorListResultModel<List<UITableNode>> errorResult = new ErrorListResultModel<List<UITableNode>>();
            errorResult.setErrdes(e.getMessage());
            result = errorResult;
        }

        return result;
    }

    @Override
    @MethodChinaName(cname = "获取列信息树形实例数据")
    @RequestMapping(method = {RequestMethod.POST, RequestMethod.GET}, value = "GetColTree")
    public @ResponseBody
    ListResultModel<List<UIColNode>> getColTree(String tableName, String configKey) {
        ListResultModel<List<UIColNode>> result = new ListResultModel<List<UIColNode>>();

        try {
            List<UIColNode> colNodes = new ArrayList<UIColNode>();
            MetadataFactory factory = getClient().getDbFactory(configKey);
            List<ColInfo> cols = factory.getTableInfo(tableName).getColList();
            for (ColInfo col : cols) {
                colNodes.add(new UIColNode(col));
            }
            result.setData(colNodes);
        } catch (Exception e) {
            ErrorListResultModel<List<UIColNode>> errorResult = new ErrorListResultModel<List<UIColNode>>();
            errorResult.setErrdes(e.getMessage());
            result = errorResult;
        }

        return result;
    }


    @Override
    @MethodChinaName(cname = "SQl执行监控")
    @RequestMapping(method = RequestMethod.GET, value = "getSqlCountInfo")
    public @ResponseBody
    ListResultModel<List<SqlExcuteInfo>> getSqlCountInfo(String configKey) {
        ListResultModel<List<SqlExcuteInfo>> result = new ListResultModel<List<SqlExcuteInfo>>();
        try {
            MetadataFactory factory = getClient().getDbFactory(configKey);
            result.setData(factory.getSqlCountInfo());
        } catch (JDSException e) {
            ErrorListResultModel<List<SqlExcuteInfo>> errorResult = new ErrorListResultModel<List<SqlExcuteInfo>>();
            errorResult.setErrdes(e.getMessage());
            result = errorResult;
        }

        return result;
    }

    @Override
    @MethodChinaName(cname = "SQl执行详细信息")
    @RequestMapping(method = RequestMethod.GET, value = "getSqlExcuteInfos")
    public @ResponseBody
    ListResultModel<List<ProfiledConnectionEntry>> getSqlExcuteInfos(String configKey, SqlType type) {
        ListResultModel<List<ProfiledConnectionEntry>> resultModel = new ListResultModel<List<ProfiledConnectionEntry>>();
        try {
            MetadataFactory factory = getClient().getDbFactory(configKey);
            resultModel = PageUtil.getDefaultPageList(factory.getSqlExcuteInfos(type));
        } catch (JDSException e) {
            ErrorListResultModel errorResult = new ErrorListResultModel();
            errorResult.setErrdes(e.getMessage());
            resultModel = errorResult;
        }
        return resultModel;
    }

    @Override
    @MethodChinaName(cname = "开启监控")
    @RequestMapping(method = RequestMethod.GET, value = "startSqlMonitor")
    public @ResponseBody
    ResultModel<Boolean> startSqlMonitor(String configKey) {
        ResultModel<Boolean> resultModel = new ResultModel<Boolean>();
        try {
            MetadataFactory factory = getClient().getDbFactory(configKey);
            factory.startSqlMonitor();
        } catch (JDSException e) {
            ErrorResultModel errorResult = new ErrorResultModel();
            errorResult.setErrdes(e.getMessage());
            resultModel = errorResult;
        }
        return resultModel;
    }

    @Override
    @MethodChinaName(cname = "停止监控")
    @RequestMapping(method = RequestMethod.GET, value = "stopSqlMonitor")
    public @ResponseBody
    ResultModel<Boolean> stopSqlMonitor(String configKey) {
        ResultModel<Boolean> resultModel = new ResultModel<Boolean>();
        try {
            MetadataFactory factory = getClient().getDbFactory(configKey);
            factory.stopSqlMonitor();
        } catch (JDSException e) {
            ErrorResultModel errorResult = new ErrorResultModel();
            errorResult.setErrdes(e.getMessage());
            resultModel = errorResult;
        }
        return resultModel;
    }

    @Override
    @MethodChinaName(cname = "重SQL监控")
    @RequestMapping(method = RequestMethod.GET, value = "resetStatistics")
    public @ResponseBody
    ResultModel<Boolean> resetStatistics(String configKey) {
        ResultModel<Boolean> resultModel = new ResultModel<Boolean>();
        try {
            MetadataFactory factory = getClient().getDbFactory(configKey);
            factory.resetStatistics();
        } catch (JDSException e) {
            ErrorResultModel errorResult = new ErrorResultModel();
            errorResult.setErrdes(e.getMessage());
            resultModel = errorResult;
        }
        return resultModel;
    }


    @Override
    @MethodChinaName(cname = "创建表")
    @RequestMapping(method = RequestMethod.POST, value = "CreateTable")
    public @ResponseBody
    ResultModel<Boolean> createTable(@RequestBody TableInfo info) {
        ResultModel<Boolean> result = new ResultModel<Boolean>();

        try {

            MetadataFactory factory = getClient().getDbFactory(info.getConfigKey());
            factory.createTableByInfo(info);
        } catch (Exception e) {
            ErrorResultModel<Boolean> errorResult = new ErrorResultModel<Boolean>();
            errorResult.setErrdes(e.getMessage());
            result = errorResult;
        }
        return result;
    }

    @Override
    @MethodChinaName(cname = "获取所有库表")
    @RequestMapping(method = RequestMethod.POST, value = "getAllTableTrees")
    public @ResponseBody
    ListResultModel<List<UITopNode>> getAllTableTrees(String text, String configKey, String pattern) {
        List<UITableNode> tableNodes = new ArrayList<UITableNode>();
        ListResultModel<List<UITopNode>> resultModel = new ListResultModel<List<UITopNode>>();
        MetadataFactory factory = null;
        try {
            factory = getClient().getDbFactory(configKey);
            List<UITopNode> toptableNodes = new ArrayList<UITopNode>();
            UITopNode simpNode = new UITopNode("All_", "所有库表", null, configKey);
            List<TableInfo> tables = factory.getTableInfos(pattern);
            for (TableInfo tableInfo : tables) {
                simpNode.addSub(new UITableNode(tableInfo));
            }
            toptableNodes.add(simpNode);
            resultModel.setData(toptableNodes);
        } catch (Exception e) {
            ErrorListResultModel<List<UITopNode>> errorResult = new ErrorListResultModel<List<UITopNode>>();
            errorResult.setErrdes(e.getMessage());
            resultModel = errorResult;
        }


        return resultModel;

    }


    public ESDClient getClient() {

        ESDClient client = null;
        try {
            client = ESDFacrory.getESDClient();
        } catch (JDSException e) {
            e.printStackTrace();
        }
        return client;
    }

}